package org.Image.management.ViewService.Game;

import javafx.collections.FXCollections;
import javafx.event.ActionEvent;
import javafx.fxml.FXML;
import javafx.scene.control.Alert;
import javafx.scene.control.TableColumn;
import javafx.scene.control.TableView;
import javafx.scene.control.cell.PropertyValueFactory;
import javafx.scene.image.Image;
import javafx.scene.layout.VBox;
import javafx.stage.StageStyle;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.Image.management.SpringDataService.Pojo.Result.Result;
import org.Image.management.SpringDataService.Service.Controller.StorageController;
import org.Image.management.SpringDataService.Service.StorageIo.Pojo.Mapper.FileStorage;
import org.Image.management.SpringDataService.Service.Sys_User.Pojo.dto.UpdateUserNameRequest;
import org.Image.management.SpringDataService.Service.Sys_User.controller.UserController;
import org.Image.management.ViewCofig.file.FxmlPath;
import org.Image.management.ViewCofig.file.IconPath;
import org.Image.management.ViewController.MainViewApp;
import org.Image.management.ViewService.Game.CopyUtils.CopySaveImage;
import org.Image.management.ViewService.Game.Node.ImageZoomPane;
import org.Image.management.ViewService.Game.pojo.TableImage;
import org.Image.management.ViewService.utils.ByPieceToolMethod;
import org.Image.management.ViewService.utils.informationalTips;
import org.Image.management.utils.UserIdThreadLocalStorage;
import org.springframework.stereotype.Controller;

import java.io.File;
import java.util.List;
import java.util.Map;
import java.util.Objects;

@Slf4j
@Controller
@RequiredArgsConstructor
public class GameController {
    private final StorageController storageController;
    private final CopySaveImage copySaveImage;
    private final UserController userController;
    @FXML
    public VBox showBox;
    @FXML
    public TableView<TableImage> Show;
    //显示图片
    @FXML
    public TableColumn<?, ?> displayPicture;
    //设置
    @FXML
    public TableColumn<?, ?> setUp;
    @FXML
    public TableColumn<?, ?> remark;

    //------------------定义数据类型------------------------//
    private ImageZoomPane imageZoomPane;

    // 当前展示的文件信息
    private FileStorage InformationAboutFileCurrentlyDisplayed;

    // 当前登录的用户
    private Long userid;

    @FXML
    void initialize() {
        userid = Long.valueOf(UserIdThreadLocalStorage.getUserToken());

        imageZoomPane = new ImageZoomPane();
        showBox.getChildren().add(imageZoomPane);

        // 设置列 PropertyValueFactory 设置列的显示数据 反射 arrayList 属性
        displayPicture.setCellValueFactory(new PropertyValueFactory<>("HImage"));
        setUp.setCellValueFactory(new PropertyValueFactory<>("operatorButton"));
        remark.setCellValueFactory(new PropertyValueFactory<>("noteTextLabel"));
        UpdateSaveImage();
    }

    //清除重置事件
    @FXML
    private void clear(ActionEvent actionEvent) {
        InformationAboutFileCurrentlyDisplayed = null;
        imageZoomPane.initializeComponents();
    }

    //更新
    private void UpdateSaveImage() {
        // 获取数据库 图片信息
        Result<?> result = storageController.getPicture(userid);

        if (!result.isSuccess()) {
            log.info("失败 ： {}", result.getMessage());
            return;
        }

        if (result.getData() instanceof List<?> data) {
            @SuppressWarnings("unchecked")
            List<FileStorage> fileStorageList = (List<FileStorage>) data;

            UpdateSaveImage(fileStorageList);
        }
    }

    private void UpdateSaveImage(List<FileStorage> data) {
        List<TableImage> tableImages = copySaveImage.ListFileStorageToTableImage(data, this::setFileStorageToTableImage);
        Show.setItems(FXCollections.observableList(tableImages));
    }

    //添加图片
    @FXML
    public void AddAnImage(ActionEvent actionEvent) throws Exception {
        // 获取文件
        File showOpenDialogFile = MainViewApp.setResizable.getShowOpenDialogFile();
        if (Objects.isNull(showOpenDialogFile)) {
            return;
        }
        informationalTips.textEntryDialogBox(StageStyle.UTILITY, "备注", "请输入图片备注", true, (event, textInputDialog) -> {
            String text = textInputDialog.getEditor().getText();

            //完成图片上传
            storageController.uploadFile(showOpenDialogFile, userid, text);

            UpdateSaveImage();
        });
    }

    // 查询图片
    @FXML
    public void Find(ActionEvent actionEvent) {
        informationalTips.textEntryDialogBox(StageStyle.UTILITY, "输入查询的名称", "请输入查询的名称", false, (event, textInputDialog) -> {
            String inquireString = textInputDialog.getEditor().getText();
            if (inquireString.isBlank()) {
                UpdateSaveImage();
                return;
            }

            // 需要完成查询图片
            Result<?> result = storageController.inquireString(userid, inquireString);

            if (!result.isSuccess()) {
                log.error("查询失败{}", result.getMessage());
                return;
            }

            if (result.getData() instanceof List<?> data) {
                @SuppressWarnings("unchecked")
                List<FileStorage> fileStorageList = (List<FileStorage>) data;

                UpdateSaveImage(fileStorageList);
            }
        });
    }

    // 保存图片
    @FXML
    public void SaveFiles(ActionEvent actionEvent) {
        log.info("保存图片{}", InformationAboutFileCurrentlyDisplayed);
        if (InformationAboutFileCurrentlyDisplayed == null) {
            informationalTips.AlertDialogBox(Alert.AlertType.INFORMATION, IconPath.PICTURE_FILLING.getIconURL(), "请选择图片", "", "保存图片");
            return;
        }
        // 获取图片路径
        File path = new File(InformationAboutFileCurrentlyDisplayed.getPath());
        // 获取图片名称
        String name = InformationAboutFileCurrentlyDisplayed.getName();
        // 获取选择器选择 文件 位置
        File file = MainViewApp.setResizable.getDirectoryChooserSelectDirectory();

        ByPieceToolMethod.writeToLocal(path, file, name);

    }

    //修改密码
    @FXML
    public void ChangePassword(ActionEvent actionEvent) {
        MainViewApp.setResizable.ChangePassword((value) -> {
            value.setUserId(userid);
            // 修改密码
            Result<?> result = userController.modifyPassword(value);
            if (!result.isSuccess()) {
                informationalTips.AlertDialogBox(Alert.AlertType.ERROR, IconPath.CRY_FILLING.getIconURL(), "", result.getMessage(), "修改密码 失败");
                return;
            }

            informationalTips.AlertDialogBox(Alert.AlertType.ERROR, IconPath.EMAIL.getIconURL(), "", result.getMessage(), "修改密码成功");
            MainViewApp.setResizable.changeView(FxmlPath.Login, false, true);
            UserIdThreadLocalStorage.clear();

        });
    }

    //修改用户名
    @FXML
    public void ChangeUserName(ActionEvent aactionEvent) {
        MainViewApp.setResizable.ModifyUsername((value) -> {
            // 修改用户名
            Result<?> result = userController.modifyUserName(new UpdateUserNameRequest(userid,value));
            if (!result.isSuccess()) {
                informationalTips.AlertDialogBox(Alert.AlertType.ERROR, IconPath.CRY_FILLING.getIconURL(), "", result.getMessage(), "注销账号 失败");
                return;
            }
            log.info("修改用户名{}", value);
            MainViewApp.setResizable.changeView(FxmlPath.Login,false,true);
            UserIdThreadLocalStorage.clear();
        });
    }

    //注销账号
    @FXML
    public void CancelYourAccount(ActionEvent actionEvent) {
        informationalTips.AlertDialogBox(Alert.AlertType.CONFIRMATION, IconPath.DELETE_FILLING.getIconURL(), "确定注销账号?", "注销账号", "注销账号", event -> {
            // 注销账号
            Result<?> result = userController.deleteUser(userid);
            if (!result.isSuccess()) {
                informationalTips.AlertDialogBox(Alert.AlertType.ERROR, IconPath.CRY_FILLING.getIconURL(), "", result.getMessage(), "注销账号 失败");
                return;
            }
            MainViewApp.setResizable.changeView(FxmlPath.Login,false,true);
            UserIdThreadLocalStorage.clear();
        });
    }

    //退出登录
    @FXML
    public void SignOut(ActionEvent actionEvent) {
        MainViewApp.setResizable.changeView(FxmlPath.Login, false, true);
        // 清除用户id
        UserIdThreadLocalStorage.clear();
    }

    /***
     *
     * @param UpdateSaveImageData -> 更改图片
     *            Map key 为 ：
     *                   更改的类别 (TheCategory) ：
     *                          value 为 String ：
     *                                      ReviseActionEvent -> 修改图片
     *                                      ShowActionEvent -> 显示图片
     *                                      DetActionEvent -> 删除图片
     *                                      ReviseDescriptionActionEvent -> 修改备注信息
     *                   当前FileStorage数据 (FileStorageData):
     *                          value 为：FileStorage 类
     *                   自定义数据 (Data) :
     *                          value 为: 自定义数据 请看各自实现
     */
    private void setFileStorageToTableImage(Map<String, Object> UpdateSaveImageData) {
        String theCategory = (String) UpdateSaveImageData.get("TheCategory");
        switch (theCategory) {
            case "ShowActionEvent" -> {
                FileStorage FileData = (FileStorage) UpdateSaveImageData.get("FileStorage");

                Image image = (Image) UpdateSaveImageData.get("Data");
                imageZoomPane.setImage(image, FileData);
                InformationAboutFileCurrentlyDisplayed = (FileStorage) UpdateSaveImageData.get("FileStorage");
            }

            case "ReviseActionEvent" -> {
                log.info("修改图片");

                imageZoomPane.initializeComponents();
                FileStorage FileDataFileData = (FileStorage) UpdateSaveImageData.get("FileStorage");
                File CustomData = (File) UpdateSaveImageData.get("Data");
                //  修改数据库图片
                //  imageDatabaseOperations.reviseImage(imageUId, showOpenDialogFile);
                storageController.reviseImage(userid,FileDataFileData.getUuid(),CustomData);

                UpdateSaveImage();
                InformationAboutFileCurrentlyDisplayed = null;
            }

            case "DetActionEvent" -> {
                String imageUId = (String) UpdateSaveImageData.get("Data");

                // 删除数据库图片
                // imageDatabaseOperations.DeleteImage(imageUId);
                imageZoomPane.initializeComponents();
                InformationAboutFileCurrentlyDisplayed = null;
                storageController.deleteFile(imageUId, userid);
                UpdateSaveImage();

            }
            case "ReviseDescriptionActionEvent" -> {
                log.info("修改备注信息");
                FileStorage FileData = (FileStorage) UpdateSaveImageData.get("FileStorage");
                String remark = (String) UpdateSaveImageData.get("Data");
                // 需要完成修改备注信息
                // imageDatabaseOperations.reviseRemark(remark, imageUId);
                storageController.reviseRemark(FileData.getUuid(), userid, remark);
                InformationAboutFileCurrentlyDisplayed = null;
                UpdateSaveImage();
            }
            default -> {
                log.info("错误： {}", theCategory);
            }
        }
    }
}